/**
 * 邮件服务工具模块
 * @author HalRui
 * @version 1.0.0
 * @description 基于Nodemailer的邮件发送服务，提供邮件发送功能
 * @date 2025年9月27日
 */

const nodemailer = require('nodemailer');
const path = require("path");

const config = require("../env.config.json");

// 在transport配置中添加连接超时和调试信息


const transport = nodemailer.createTransport({
    host: config.email.host,
    port: config.email.port,
    secure: true,
    auth: {
        user: config.email.user,
        pass: config.email.pass
    },
    connectionTimeout: 10000 // 10秒连接超时
})

//发送邮件
const sendEmail = async (to, subject, content, isHtml = false) => {
    const options = {
        from: config.email.from,             //发信人
        to: to,                              //收信人
        subject: subject,                    //主题
    };

    // 根据是否是HTML设置内容
    if (isHtml) {
        options.html = content;  // HTML内容
    } else {
        options.text = content;  // 纯文本内容
    }

    try {
        // 先验证连接
        await transport.verify();
        console.log('126邮件服务器连接正常');

        const info = await transport.sendMail(options);
        console.log(`邮件已发送给 ${to} sent successfully ${info.messageId}`);
        return {
            success: true,
            message: info.messageId
        }
    } catch (err) {
        console.log(`邮件发送失败-${to}`, err.message);
        return {
            success: false,
            message: err.message
        }
    }
}

module.exports = sendEmail;